const express = require('express');
const md5 = require('md5');
const UserModel = require('../../models/UserModel');
const JWT = require('jsonwebtoken');
const {sercet} = require('../../config/config');

const router = express.Router();

router.post('/login', (req, res) => {
    let {username, password} = req.body;

    UserModel.findOne({username: username, password: md5(password)})
    .then((data) => {
        let token = JWT.sign({
            username: data.username,
            _id: data._id
        }, sercet, {
            expiresIn: 60 * 60 * 24 * 7
        })

        res.json({
            code: '0000',
            msg: '登录成功',
            data: token
        })
        
    }).catch(() => {
        res.status(500).send('登录失败');
        res.json({
            code:'2001',
            msg: '数据库读取失败2',
            data: null
        })
    })
})

router.post('/logout', (req, res) => {
    req.session.destroy(() => {
        res.render('success', {msg: '退出成功', url:'/login'});
    });
})

module.exports = router;
